<!--
 * @Description: 课程编辑弹窗
 * @Author: liyujie
 * @Date: 2021/10/18
 * @Last Modified by: liyujie
 * @Last Modified time: 2021/10/18
-->
<template>
    <section class="wrapper">
        <el-dialog
            title="编辑课程"
            :visible.sync="dialogVisible"
            width="680px"
            :close-on-click-modal="false"
            @close="$emit('close')"
        >
            <div class="dialog-content">
                <el-form
                    :model="ruleForm"
                    :rules="rules"
                    ref="ruleForm"
                    label-width="108px"
                    size="medium"
                    @submit.native.prevent
                >
                    <el-form-item
                        label="课程名称"
                        prop="course_name"
                        class="is-required"
                    >
                        <el-input
                            v-model="ruleForm.course_name"
                            clearable
                            style="width: 384px"
                            placeholder="请输入课程名称"
                        />
                    </el-form-item>
                    <el-form-item
                        label="课程目录"
                        prop="type_no"
                        class="is-required"
                    >
                        <el-cascader
                            v-model="ruleForm.type_no"
                            clearable
                            filterable
                            style="width: 384px"
                            :options="typeList"
                            :props="{
                                label: 'title',
                                value: 'no',
                                children: 'children',
                                checkStrictly: true,
                                emitPath: false
                            }"
                        />
                    </el-form-item>
                    <el-form-item
                        label="课程上传"
                        prop="file_path"
                    >
                        <el-upload
                            class="upload-demo"
                            action="https://jsonplaceholder.typicode.com/posts/"
                            :http-request="fnUploadFile"
                            accept="video/MP4"
                            :show-file-list="false"
                            :disabled="uploadingFile"
                        >
                            <el-button
                                size="small"
                                type="primary"
                                :disabled="uploadingFile"
                            >
                                点击上传
                            </el-button>
                            <span
                                slot="tip"
                                class="el-upload__tip"
                                style="margin-left: 10px"
                            >
                                只能上传"mp4"格式文件
                            </span>
                        </el-upload>
                        <ul class="el-upload-list el-upload-list--text">
                            <li
                                class="el-upload-list__item is-uploading"
                                :class="{'is-uploading': item.percent < 100, 'is-success': item.percent >= 100}"
                                v-for="(item, index) in ruleForm.fileList"
                                :key="index"
                                @click="previewVideo(ruleForm.file_preview_path)"
                            >
                                <a class="el-upload-list__item-name">
                                    <i class="el-icon-document"/>
                                    {{ item.name }}
                                </a>
                                <label class="el-upload-list__item-status-label">
                                    <i class="el-icon-upload-success el-icon-circle-check"/>
                                </label>
                                <i
                                    class="el-icon-close"
                                    @click.stop="fnUploadRemove"
                                />
                                <div
                                    role="progressbar"
                                    aria-valuenow="11"
                                    aria-valuemin="0"
                                    aria-valuemax="100"
                                    class="el-progress el-progress--line"
                                    v-if="item.percent < 100"
                                >
                                    <div class="el-progress-bar">
                                        <div
                                            class="el-progress-bar__outer"
                                            style="height: 2px;"
                                        >
                                            <div
                                                class="el-progress-bar__inner"
                                                :style="'width: '+item.percent+'%;'"
                                            />
                                        </div>
                                    </div>
                                    <div
                                        class="el-progress__text"
                                        style="font-size: 12.8px;"
                                    >
                                        {{ item.percent }}%
                                    </div>
                                </div>
                            </li>
                        </ul>
                    </el-form-item>
                    <el-form-item
                        label="上架状态"
                        prop="course_status"
                    >
                        <el-radio-group
                            v-model="ruleForm.course_status"
                        >
                            <el-radio :label="1">上架</el-radio>
                            <el-radio :label="0">下架</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item
                        label="视频推广"
                    >
                        <div
                            v-if="ruleForm.recommend_type"
                            class="link-text"
                            @click="handleRecommendLink(ruleForm.recommend_type, ruleForm.recommend_no)"
                        >
                            <div class="recommend-title">
                                {{ ruleForm.recommend_type | recommendTypeFilter }}：{{ ruleForm.recommend_title }}
                            </div>
                        </div>
                        <div v-else>--</div>
                    </el-form-item>
                    <el-form-item
                        label="显示浏览量"
                        prop="course_view_base"
                    >
                        <el-input-number
                            v-model="ruleForm.course_view_base"
                            placeholder="请输入"
                            :step="1"
                            step-strictly
                            :controls="false"
                            :min="0"
                        />
                    </el-form-item>
                    <template v-if="rowStatus === 0">
                        <el-form-item
                            label="审核状态"
                            prop="audit_status"
                        >
                            <el-radio-group
                                v-model="ruleForm.audit_status"
                            >
                                <el-radio :label="1">审核通过</el-radio>
                                <el-radio :label="-1">审核驳回</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item
                            label="驳回原因"
                            prop="audit_reason"
                            class="is-required"
                            v-if="ruleForm.audit_status === -1"
                        >
                            <el-input
                                v-model="ruleForm.audit_reason"
                                type="textarea"
                                style="width: 384px"
                                placeholder="请输入驳回原因"
                                :autosize="{ minRows: 4}"
                            />
                        </el-form-item>
                    </template>
                </el-form>
            </div>
            <div
                class="dialog-footer"
                style="padding-top: 12px"
            >
                <el-button
                    size="medium"
                    style="width: 120px"
                    @click="dialogVisible = false"
                >
                    取消
                </el-button>
                <el-button
                    type="primary"
                    size="medium"
                    style="width: 120px;margin-left: 32px"
                    @click="handleConfirm()"
                >
                    {{ rowStatus === 0 ? '完成审核' : '确认' }}
                </el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>
import {deepClone} from "@/assets/js/utils";
import Vue from "vue";

const Dialog = {
    name: "CourseEditDialog",
    props: {
        courseNo: {
            type: String,
            default: ''
        },
        rowStatus: {
            type: Number,
            default: 0
        },
        typeList: {
            type: Array,
            default: () => {
                return [];
            }
        },
        _parent: {
            type: Object
        }
    },
    filters: {
        recommendTypeFilter(val) {
            switch (val) {
                case 1:
                    return '职位名称';
                case 2:
                    return '任务标题';
                case 3:
                    return '商品名称';
                case 4:
                    return '店铺推广';
                default:
                    return '--';
            }
        },
    },
    data() {
        return {
            dialogVisible: false,
            ruleForm: {
                course_no: '',
                // 课程名称
                course_name: '',
                // 分类编号
                type_no: '',
                // 文件
                file_path: '',
                file_type: '',
                file_name: '',
                file_ext: '',
                file_size: '',
                file_cover: '',
                // 浏览量
                course_view_base: '',
                // 上架状态
                course_status: 1,
                // 审核状态
                audit_status: 1,
                // 审核原因
                audit_reason: '',
                fileList: []
            },
            rules: {
                course_name: [
                    {required: true, message: '请填写课程名称', trigger: 'blur'},
                ],
                type_no: [
                    {required: true, message: '请选择分类', trigger: 'change'},
                ],
                file_path: [
                    {required: true, message: '请上传视频文件', trigger: 'change'},
                ],
                audit_reason: [
                    {required: true, message: '请输入驳回原因', trigger: 'blur'},
                ],
            },
            uploadingFile: false
        };
    },
    watch: {
        courseNo: {
            handler(val) {
                this.ruleForm.course_no = val;
            },
            immediate: true
        }
    },
    mounted() {
        this.getData();
    },
    methods: {

        /**
         * 显示弹窗
         */
        show() {
            this.dialogVisible = true;
        },

        /**
         * 显示弹窗
         */
        close() {
            this.dialogVisible = false;
        },

        /**
         * 获取数据
         */
        getData() {
            let params = {
                course_no: this.ruleForm.course_no
            };

            this.$post('/student/course%5Cget', params, resp => {
                if (resp.code === 1) {
                    let data = deepClone(resp.data);

                    this.ruleForm = data;
                    this.$set(this.ruleForm, 'fileList', [{
                        name: data.file_name,
                        url: data.file_path,
                        percent: 100
                    }]);
                    this.ruleForm.audit_status = 1;
                } else {
                    this.$notify({
                        title: '提示',
                        message: resp.msg,
                        duration: 2000,
                        type: 'warning'
                    });
                }
            });
        },

        /**
         * 点击确定
         */
        handleConfirm() {
            this.$refs.ruleForm.validate((valid) => {
                if(valid) {
                    let params = deepClone(this.ruleForm);
                    let url = this.rowStatus === 0 ? '/student/course%5Caudit' : '/student/course%5Csave';

                    this.$post(url, params, resp => {
                        if (resp.code === 1) {
                            this.$notify({
                                title: '提示',
                                message: '操作成功',
                                duration: 2000,
                                type: 'success'
                            });
                            this.$emit('confirm', true);
                        } else {
                            this.$notify({
                                title: '提示',
                                message: resp.msg,
                                duration: 2000,
                                type: 'warning'
                            });
                        }
                    });
                }
            });
        },

        fnUploadRemove(e, fileList) {
            this.ruleForm.fileList = [];
            this.ruleForm.file_path = '';
            this.ruleForm.file_type = '';
            this.ruleForm.file_name = '';
            this.ruleForm.file_ext = '';
            this.ruleForm.file_size = '';
            this.ruleForm.file_cover = '';
            if (this.cancel) {
                this.cancel();
                this.cancel = null;
                this.uploadingFile = false;
            }
        },
        fnGetUploadAuth(name, callback) {
            this.$post('/student/course%5Cupload_auth', {
                file_name: name,
                file_type: 'video'
            }, resp => {
                if (resp.code === 1) {
                    callback(resp.data);
                } else {
                    this.$message({
                        type: 'warning',
                        message: resp.msg,
                        center: true
                    });
                }
            });
        },
        fnUploadFile(event) {
            this.fnGetUploadAuth(event.file.name, (data) => {
                this.ruleForm.file_ext = data.ext;
                let file = {
                    name: event.file.name,
                    url: '',
                    percent: 0,
                };

                this.ruleForm.fileList = [file];

                //开始上传文件
                let timeTmp = new Date().getTime();

                this.currTime = timeTmp;

                let fd = new FormData();

                fd.append('policy', data.body.policy);
                fd.append('signature', data.body.signature);
                fd.append('file', event.file);
                this.uploadingFile = true;

                this.$upload({
                    url: data.api,
                    data: fd,
                    progress: (e) => {
                        console.log(e);
                        if (this.currTime != timeTmp) {
                            return;
                        }
                        file.percent = e.percent.toFixed(1) * 1;
                    },
                    success: resp => {
                        if (this.currTime != timeTmp) {
                            return;
                        }
                        this.uploadingFile = false;
                        this.cancel = null;
                        if (resp.code == 200) {
                            this.ruleForm.file_path = resp.url;
                            this.ruleForm.file_name = event.file.name;
                            this.ruleForm.file_size = resp.file_size;
                            this.ruleForm.file_preview_path = '';
                            file.url = resp.url;
                        } else {
                            if (resp.code == -999) {
                                return;
                            }
                            this.$notify.error({
                                title: '错误',
                                duration: 2000,
                                message: resp.msg || '上传失败，请稍后重试'
                            });
                        }
                    }
                });
            });
        },

        /**
         * 预览视频
         * @param url
         */
        previewVideo(url) {
            if (!url) {
                // this.$message.warning('视频地址为空');
                return;
            }

            window.open(url, 'videoPreview');
        },

        /**
         * 跳转
         * @param type
         * @param no
         */
        handleRecommendLink(type, no) {
            this._parent.handleRecommendLink(type, no);
        },
    }
};

export default Dialog;

const courseEditDialog = function (config) {
    return new Promise((resolve) => {
        const DialogConstructor = Vue.extend(Dialog);
        const instance = new DialogConstructor({
            propsData: config,
        }).$mount();

        instance.$on("close", function () {
            setTimeout(() => {
                document.body.removeChild(instance.$el);
                instance.$destroy();
            }, 300);
            resolve(false);
        });
        instance.$on("confirm", function (data) {
            instance.close();
            resolve(data);
        });
        document.body.appendChild(instance.$el);
        instance.dialogVisible = true;
    });
};

export {courseEditDialog};
</script>

<style scoped lang="less">
.wrapper {
    .dialog-content {
        display: flex;
        flex-direction: column;
        padding: 0 32px;
        .recommend-title {
            line-height: 20px;
        }
    }

    .dialog-footer {
        display: flex;
        justify-content: center;
    }
}

/deep/ .el-dialog__header {
    padding-top: 10px;
    box-shadow: 0 1px 0 0 rgba(233, 233, 233, 1);
    display: flex;
    align-items: center;
    background: #FAFAFA;
    border-radius: 4px 4px 0 0;

    .el-dialog__title {
        font-weight: 500;
        color: #333;
        font-size: 14px;
    }

    .el-icon-close:before {
        color: rgb(194, 194, 194);
        font-size: 17px;
        font-weight: bold;
    }

    .el-dialog__headerbtn {
        top: 14px;
    }
}

/deep/ .el-dialog__body {
    padding: 24px 32px;
}

/deep/ .el-textarea__inner {
    resize: none;
}

/deep/ .el-input-number .el-input__inner {
    text-align: left;
}

/deep/ .el-dialog {
    margin-top: 10vh !important;
}

.is-required {
    .el-form-item__label {
        &:before {
            content: "*";
            display: inline-block;
            color: #F56C6C;
        }
    }
}

.link-text {
    color: #20A0FF;
    cursor: pointer;
    text-overflow: ellipsis;
    overflow: hidden;
}
</style>
